package handlers

import (
	pb "kitest1"
	mymidd "kitest1/calc-service/middlewares"
	"kitest1/calc-service/svc"
	"os"
	"time"

	"github.com/go-kit/kit/log"
	kitprometheus "github.com/go-kit/kit/metrics/prometheus"
	stdprometheus "github.com/prometheus/client_golang/prometheus"
	"golang.org/x/time/rate"
)

// WrapEndpoints accepts the service's entire collection of endpoints, so that a
// set of middlewares can be wrapped around every middleware (e.g., access
// logging and instrumentation), and others wrapped selectively around some
// endpoints and not others (e.g., endpoints requiring authenticated access).
// Note that the final middleware wrapped will be the outermost middleware
// (i.e. applied first)
func WrapEndpoints(in svc.Endpoints) svc.Endpoints {

	// Pass a middleware you want applied to every endpoint.
	// optionally pass in endpoints by name that you want to be excluded
	// e.g.
	// in.WrapAllExcept(authMiddleware, "Status", "Ping")

	// Pass in a svc.LabeledMiddleware you want applied to every endpoint.
	// These middlewares get passed the endpoints name as their first argument when applied.
	// This can be used to write generic metric gathering middlewares that can
	// report the endpoint name for free.
	// github.com/metaverse/truss/_example/middlewares/labeledmiddlewares.go for examples.
	// in.WrapAllLabeledExcept(errorCounter(statsdCounter), "Status", "Ping")

	// How to apply a middleware to a single endpoint.
	// in.ExampleEndpoint = authMiddleware(in.ExampleEndpoint)
	ratebucket := rate.NewLimiter(rate.Every(time.Second*1), 30)
	in.WrapAllExcept(mymidd.LimitMiddleware(ratebucket))
	return in
}

var g_l log.Logger

func WrapService(in pb.CalcServer) pb.CalcServer {
	// l := log.New(os.Stderr, "", log.LstdFlags)
	svc := mymidd.NewLogMiddle(in, g_l)

	fieldKeys := []string{"method"}
	requestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Namespace: "raysonxin",
		Subsystem: "arithmetic_service",
		Name:      "request_count",
		Help:      "Number of requests received.",
	}, fieldKeys)

	requestLatency := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{
		Namespace: "raysonxin",
		Subsystem: "arithemetic_service",
		Name:      "request_latency",
		Help:      "Total duration of requests in microseconds.",
	}, fieldKeys)
	svc = mymidd.NewMetricMiddle(svc, g_l, requestCount, requestLatency)
	return svc
}

func init() {
	g_l = log.NewLogfmtLogger(os.Stderr)
	//注册consul
	registar := mymidd.Register("127.0.0.1", "8500", "172.20.0.1", "5050", g_l)
	// 	//启动前执行注册
	registar.Register()
}
